import json
import os

def export_annotations(video_name, fps, extract_frame_path, frame_count, modality, annotations, output_json):
    """
    Build annotation data and export to a JSON file.
    
    Args:
      video_name (str): Source video file name.
      fps (float): Frames per second.
      extract_frame_path (str): Relative folder path for extracted frames.
      frame_count (int): Number of frames extracted.
      modality (str): Modality identifier (e.g., "T" or "V").
      annotations (list): List of annotations. Each annotation is a dict with:
          - frame_file: the frame image filename.
          - bbox_info: dict with x, y, width, height.
          - metadata_info: dict with original_frame, video_timestamp,
                           srt_timestamp, diff_time, camera, gps, attitude.
          - reid_id: integer identifier.
      output_json (str): Path to save the JSON file.
    """
    data = {
        "video_name": video_name,
        "fps": fps,
        "extract_frame_file_from_project": extract_frame_path,
        "frame_count": frame_count,
        "modality": modality,
        "annotations": annotations
    }
    
    os.makedirs(os.path.dirname(output_json), exist_ok=True)
    with open(output_json, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
    print(f"[INFO] Annotations exported to: {output_json}")

def generate_annotation(frame_file, original_frame, video_timestamp, srt_timestamp, diff_time, camera, gps, attitude, x, y, width, height, reid_id):
    """
    Generate a single annotation from individual frame metadata and bounding box parameters.
    
    Args:
      frame_file (str): The frame image filename.
      original_frame (int): Original frame number.
      video_timestamp (str): Timestamp in the video.
      srt_timestamp (str): Timestamp from the SRT file.
      diff_time (str): Difference time.
      camera (dict): Camera metadata including focal length and zoom ratio.
      gps (dict): GPS metadata including latitude, longitude, relative altitude, and absolute altitude.
      attitude (dict): Attitude metadata including yaw, pitch, and roll.
      x (int): x-coordinate of the bounding box.
      y (int): y-coordinate of the bounding box.
      width (int): Width of the bounding box.
      height (int): Height of the bounding box.
      reid_id (int): Identifier for the annotation.
    
    Returns:
      dict: An annotation dictionary.
    """
    metadata_info = {
        "original_frame": original_frame,
        "video_timestamp": video_timestamp,
        "srt_timestamp": srt_timestamp,
        "diff_time": diff_time,
        "camera": camera,
        "gps": gps,
        "attitude": attitude
    }
    
    return {
        "frame_file": frame_file,
        "bbox_info": {
            "x": x,
            "y": y,
            "width": width,
            "height": height
        },
        "metadata_info": metadata_info,
        "reid_id": reid_id
    }

if __name__ == '__main__':
    # Example usage with sample data:
    sample_annotations = [
        {
            "frame_file": "frame_0001.jpg",
            "bbox_info": {"x": 120, "y": 80, "width": 50, "height": 100},
            "metadata_info": {
                "original_frame": 1,
                "video_timestamp": "0:00:00",
                "srt_timestamp": "2024-12-17 16:51:44.223",
                "diff_time": "33ms",
                "camera": {"focal_len": "40.00", "dzoom_ratio": "1.00"},
                "gps": {"latitude": "31.761141", "longitude": "117.183873",
                        "rel_alt": "47.317", "abs_alt": "87.342"},
                "attitude": {"yaw": "53.9", "pitch": "-24.5", "roll": "0.0"}
            },
            "reid_id": 1
        },
        {
            "frame_file": "frame_0045.jpg",
            "bbox_info": {"x": 130, "y": 90, "width": 55, "height": 105},
            "metadata_info": {
                "original_frame": 45,
                "video_timestamp": "0:00:01.468133",
                "srt_timestamp": "2024-12-17 16:51:45.690",
                "diff_time": "33ms",
                "camera": {"focal_len": "40.00", "dzoom_ratio": "1.00"},
                "gps": {"latitude": "31.761140", "longitude": "117.183873",
                        "rel_alt": "47.370", "abs_alt": "87.395"},
                "attitude": {"yaw": "53.9", "pitch": "-24.5", "roll": "0.0"}
            },
            "reid_id": 2
        }
    ]
    
    export_annotations(
        video_name="DJI_20241217165143_0003_T.MP4",
        fps=29.97002997002997,
        extract_frame_path="Frames/DJI_20241217165143_0003/T",
        frame_count=111,
        modality="T",
        annotations=sample_annotations,
        output_json=os.path.join("d:/code/mmreid-label-tool/output", "annotations.json")
    )
